package com.lky.marshallmall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lky.common.utils.HttpUtils;
import com.lky.common.utils.PageUtils;
import com.lky.common.utils.Query;
import com.lky.marshallmall.member.dao.MemberDao;
import com.lky.marshallmall.member.dao.MemberLevelDao;
import com.lky.marshallmall.member.entity.MemberEntity;
import com.lky.marshallmall.member.entity.MemberLevelEntity;
import com.lky.marshallmall.member.exception.PhoneExistsException;
import com.lky.marshallmall.member.exception.UsernameExistsException;
import com.lky.marshallmall.member.service.MemberService;
import com.lky.marshallmall.member.vo.*;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();

        //初始化 设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        //检查用户名 手机号 是否唯一,为了controller感知异常，使用异常机制
        checkPhone(vo.getPhone());
        checkUserName(vo.getUserName());

        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setNickname(vo.getUserName());

        //密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhone(String phone) throws PhoneExistsException {
        Integer mobile = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistsException();
        }
    }

    @Override
    public void checkUserName(String userName) throws UsernameExistsException {
        Integer username = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (username > 0) {
            throw new UsernameExistsException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginAcct = vo.getLoginAcct();
        String password = vo.getPassword();
        //1.去数据库查询
        MemberEntity member = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAcct).or().eq("mobile", loginAcct));
        if (member == null) {
            //登录失败
            return null;
        } else {
            //数据库获取到的password
            String passwordDB = member.getPassword();
            //密码匹配
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, passwordDB);
            if (matches) {
                return member;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(TokenVo vo) {
        //登录和注册合并逻辑
        String uid = vo.getOpenid();
        //1.判断当前社交用户是否登录过
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //用户已经注册
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(vo.getAccessToken());
            update.setExpiresIn(vo.getExpiresIn());
            memberDao.updateById(update);
            memberEntity.setAccessToken(vo.getAccessToken());
            memberEntity.setExpiresIn(vo.getExpiresIn());
            return memberEntity;
        } else {
            //没有查到，需要注册
            MemberEntity register = new MemberEntity();
            //3.查询社交用户的账号信息
            Map<String, String> map = new HashMap<>();
            map.put("access_token", vo.getAccessToken());
            map.put("openid", vo.getOpenid());
            map.put("lang", "zh_CN");
            HttpResponse response = null;
            try {
                response = HttpUtils.doGet("https://api.weixin.qq.com", "/sns/userinfo", "get", null, map);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    UserSocialVo userSocial = JSON.parseObject(json, UserSocialVo.class);
                    //昵称
                    String nickname = userSocial.getNickname();
                    //1 man 0 woman
                    int sex = userSocial.getSex();
                    String headImgurl = userSocial.getHeadimgurl();

                    register.setNickname(nickname);
                    register.setGender(sex);
                    register.setHeader(headImgurl);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            register.setSocialUid(uid);
            register.setAccessToken(vo.getAccessToken());
            register.setExpiresIn(vo.getExpiresIn());
            memberDao.insert(register);
            return register;
        }
    }

    @Override
    public MemberEntity login(WeiboTokenVo weiboTokenVo) {
        String uid = weiboTokenVo.getUid();
        MemberDao baseMapper = this.baseMapper;
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (entity != null) {
            //登录
            MemberEntity update = new MemberEntity();
            update.setId(entity.getId());
            update.setAccessToken(weiboTokenVo.getAccess_token());
            update.setExpiresIn(Math.toIntExact(weiboTokenVo.getExpires_in()));
            baseMapper.updateById(update);
            entity.setAccessToken(weiboTokenVo.getAccess_token());
            entity.setExpiresIn(Math.toIntExact(weiboTokenVo.getExpires_in()));
            return entity;
        } else {
            //没有查到，需要注册
            MemberEntity register = new MemberEntity();
            Map<String, String> map = new HashMap<>();
            map.put("access_token", weiboTokenVo.getAccess_token());
            map.put("uid", weiboTokenVo.getUid());
            HttpResponse response = null;
            try {
                response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", null, map);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    WeiboUserInfoVo weiboUserInfoVo = JSON.parseObject(json, WeiboUserInfoVo.class);
                    //昵称
                    String nickname = weiboUserInfoVo.getScreenName();
                    //1 man 0 woman
                    String sex = weiboUserInfoVo.getGender();
                    String headImgurl = weiboUserInfoVo.getProfileImageUrl();
                    register.setNickname(nickname);
                    register.setGender("m".equals(sex) ? 1 : 0);
                    register.setHeader(headImgurl);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            register.setSocialUid(uid);
            register.setAccessToken(weiboTokenVo.getAccess_token());
            register.setExpiresIn(Math.toIntExact(weiboTokenVo.getExpires_in()));
            baseMapper.insert(register);
            return register;
        }
    }

}